<template>
    <el-container>
        <el-aside width="400px">
            <el-card class="full" shadow="hover" body-style="padding:10px">
                <el-form ref="form" :model="state.form" :rules="rules" label-width="80px">
                    <el-form-item label="产 线" prop="line">
                        <el-select v-model="state.form.line" @change="onLineChange">
                            <el-option v-for="i in state.lines" :label="i.name" :value="i.code" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="产品" prop="product">
                        <el-select v-model="state.form.product" @change="onProductChange">
                            <el-option v-for="item in state.productUsed" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="设备型号" prop="model">
                        <el-select v-model="state.form.model" @change="onModelChange">
                            <el-option v-for="item in state.modelUsed" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="[3, 4, 5].includes(state.form.wt)">
                        <el-text type="danger">请连接CAN总线设备</el-text>
                    </el-form-item>
                    <template v-if="state.form.wt === 1">
                        <el-form-item label="串 口" prop="serial.port">
                            <el-select v-model="state.form.serial.port" style="width: 82%;">
                                <el-option v-for="item in state.ports" :key="item" :label="item"
                                    :value="item"></el-option>
                            </el-select>
                            <el-button style="margin-left: 5px;" type="primary" :icon="Refresh"
                                @click="loadProts"></el-button>
                        </el-form-item>
                        <el-form-item label="波特率" prop="serial.baud_rate">
                            <el-select v-model="state.form.serial.baud_rate">
                                <el-option label="1200" :value="1200" />
                                <el-option label="4800" :value="4800" />
                                <el-option label="9600" :value="9600" />
                                <el-option label="19200" :value="19200" />
                                <el-option label="115200" :value="115200" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="数据位" prop="serial.data_bits">
                            <el-select v-model="state.form.serial.data_bits">
                                <el-option label="5" :value="5" />
                                <el-option label="6" :value="6" />
                                <el-option label="7" :value="7" />
                                <el-option label="8" :value="8" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="校验位" prop="serial.parity">
                            <el-select v-model="state.form.serial.parity">
                                <el-option label="None" :value="0" />
                                <el-option label="Odd" :value="1" />
                                <el-option label="Even" :value="2" />
                                <el-option label="Mark" :value="3" />
                                <el-option label="Space" :value="4" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="停止位" prop="serial.stop_bits">
                            <el-select v-model="state.form.serial.stop_bits">
                                <el-option label="1" :value="0" />
                                <el-option label="1.5" :value="1" />
                                <el-option label="2" :value="2" />
                            </el-select>
                        </el-form-item>
                    </template>
                    <template v-else-if="[2, 4, 5].includes(state.form.wt)">
                        <el-form-item label="IP地址" prop="ssh.host">
                            <el-input v-model="state.form.ssh.host" />
                        </el-form-item>
                        <el-form-item label="SSH账户" prop="ssh.username">
                            <el-input v-model="state.form.ssh.username" />
                        </el-form-item>
                        <el-form-item label="SSH密码" prop="ssh.password">
                            <el-input v-model="state.form.ssh.password" />
                        </el-form-item>
                    </template>
                </el-form>

                <el-button style="margin-top: 15px;" class="fr fw" type="primary" :icon="Files" @click="onWrite"
                    :loading="state.writeLoading">
                    写 入</el-button>
            </el-card>
        </el-aside>
        <el-main>
            <el-card class="full" body-class="terminal">
                <el-scrollbar>
                    <p v-for="item in state.logs">{{ item }}</p>
                </el-scrollbar>
            </el-card>
        </el-main>
    </el-container>
</template>

<script setup>
import { reactive, getCurrentInstance, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Files, Refresh } from '@element-plus/icons-vue';
import { PortsList, WriteSN, LoadLocal } from '#/go/server/Handler.js';
import { required } from '@/util/validate.js';
import { EventsOn } from '#/runtime/runtime';

const { proxy } = getCurrentInstance();
const rules = {
    line: [required],
    product: [required],
    model: [required],
    "serial.port": [required],
    "serial.baud_rate": [required],
    "serial.data_bits": [required],
    "serial.parity": [required],
    "serial.stop_bits": [required],
    "ssh.username": [required],
    "ssh.password": [required],
    "ssh.host": [required],
};

const state = reactive({
    form: {
        line: null,
        product: null,
        model: null,
        model_code: null,
        wt: null,
        serial: {
            port: "",
            baud_rate: 9600,
            data_bits: 8,
            parity: 0,
            stop_bits: 0,
        },
        ssh: {
            host: "",
            username: 'root',
            password: '',
        },
    },
    lines: [],
    product: [],
    productUsed: [],
    modelUsed: [],
    ports: [],
    logs: [],
    writeLoading: false,
})

const onLineChange = val => {
    const line = state.lines.find(v => v.code === val);
    state.form.product = null;
    state.form.model = null;
    state.form.wt = null;
    state.productUsed = state.product.filter(v => line.product.includes(v.id));
}

const onProductChange = val => {
    state.form.model = null;
    state.form.wt = null;
    state.modelUsed = state.product.find(i => i.id === val)?.model || [];
}

const onModelChange = val => {
    const model = state.modelUsed.find(v => v.id === val);
    state.form.model_code = model.no;
    state.form.wt = model.wt;
}

const onWrite = () => {
    // console.log(state.form);
    // return;

    proxy.$refs.form.validate(pass => {
        if (!pass) return;
        state.logs = [];
        const p = { ...state.form };
        state.writeLoading = true;
        WriteSN(p).catch(err => {
            ElMessage.error("失败: " + err);
        }).finally(() => {
            state.writeLoading = false;
        })
    })
}

const loadProts = async () => {
    await PortsList().then(res => state.ports = res || []);
}

const onLoadLocal = () => {
    LoadLocal().then(res => {
        console.log("本地数据加载成功", res);
        state.lines = (res.line || []).map(v => {
            v.product = v.product.split(',').map(p => parseInt(p.trim()));
            return v;
        });
        state.product = res.product || [];
    }).catch(err => {
        console.log("本地数据加载失败", err);
    });
}

onMounted(async () => {
    await loadProts();

    EventsOn("event-write-sn", res => {
        state.logs.push(res)
    })

    onLoadLocal()
})
</script>

<style scoped>
.el-table .warning-row {
    --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
    --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>